import {
  Badge,
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Dropdown,
  Form,
  Icon,
  Input,
  InputNumber,
  Menu,
  Row,
  Select,
  message,
  Popconfirm,
} from 'antd';
import React, { Component, Fragment } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import moment from 'moment';
import { StateType } from './model';
import StandardTable, { StandardTableColumnProps } from '@/components/StandardTable';
import { TableListItem, TableListPagination, TableListParams } from './data.d';

import styles from './style.less';
const R = require('ramda');
const FormItem = Form.Item;
const { Option } = Select;
const getValue = (obj: { [x: string]: string[] }) =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  manageEnterpriseApproval: StateType;
}

interface TableListState {
  modalVisible: boolean;
  updateModalVisible: boolean;
  expandForm: boolean;
  selectedRows: TableListItem[];
  formValues: { [key: string]: string };
  stepFormValues: Partial<TableListItem>;
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    manageEnterpriseApproval,
    global,
    loading,
  }: {
    manageEnterpriseApproval: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    manageEnterpriseApproval,
    global,
    loading: loading.models.rule,
  }),
)
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
  };

  componentDidMount() {
    const { dispatch, global } = this.props;
    const { userInfo } = global;

    dispatch({
      type: 'manageEnterpriseApproval/refreshState',
      payload: {
        data: {
          list: [],
          pagination: {},
        },
      },
    });

    if (R.isNil(userInfo) || R.isEmpty(userInfo)) {
      message.info('请先创建企业或加入企业');
      return;
    }

    if (!userInfo.owner) {
      message.info('当前用户没有管理企业的权限。');
      return;
    }

    dispatch({
      type: 'manageEnterpriseApproval/fetch',
      payload: {
        cstId: userInfo.id,
        creator: userInfo.creator,
        page: 1,
        size: 10,
      },
    });
  }

  columns: StandardTableColumnProps[] = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <Popconfirm
            placement="leftTop"
            onConfirm={this.handleJoinApproval.bind(this, true, record)}
            okText="是"
            cancelText="否"
            title={'是否同意加入'}
          >
            <a href="#">申请加入</a>
          </Popconfirm>

          <Divider type="vertical" />
          <Popconfirm
            placement="leftTop"
            onConfirm={this.handleJoinApproval.bind(this, false, record)}
            okText="是"
            cancelText="否"
            title={'是否拒绝加入'}
          >
            <a href="#">拒绝加入</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  handleJoinApproval = (approvalStatus, record) => {
    const { dispatch, global } = this.props;
    const { userInfo } = global;
    let values = {};
    values.cstId = record.cstid;
    values.userId = record.userid;

    if (approvalStatus) {
      values.status = '2';
    } else if (!approvalStatus) {
      values.status = '3';
    }

    dispatch({
      type: 'manageEnterpriseApproval/approval',
      payload: {
        ...values,
        onSuccess: () => {
          this.props.dispatch({
            type: 'manageEnterpriseApproval/fetch',
            payload: {
              cstId: record.cstid,
              creator: userInfo.creator,
              page: 1,
              size: 10,
            },
          });
        },
      },
    });
  };

  handleStandardTableChange = (
    pagination: Partial<TableListPagination>,
    filtersArg: Record<keyof TableListItem, string[]>,
    sorter: SorterResult<TableListItem>,
  ) => {
    const { dispatch, global } = this.props;
    const { userInfo } = global;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    params.cstId = userInfo.id;
    params.creator = userInfo.creator;

    dispatch({
      type: 'manageEnterpriseApproval/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'manageEnterpriseApproval/fetch',
        payload: values,
      });
    });
  };

  render() {
    const {
      manageEnterpriseApproval: { data },
      loading,
    } = this.props;

    const { selectedRows } = this.state;

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
